package edu.upc.clase.demo.dao.impl;

import edu.upc.clase.demo.dao.SubcategoriaDao;
import edu.upc.clase.demo.entity.Subcategoria;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class SubcategoriaDaoImpl extends SimpleJdbcDaoSupport implements SubcategoriaDao {
    
    private static Logger log = LoggerFactory.getLogger(SubcategoriaDaoImpl.class);

    @Autowired
    public SubcategoriaDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }   
    
    @Override
    public Integer insertar(Subcategoria subcategoria) {

        getJdbcTemplate().update(
                "insert into subcategoria (de_subcategoria, in_estado, categoria_id_categoria) values (?, ?, ?)",
                subcategoria.getDe_subcategoria(), subcategoria.getIn_estado(), subcategoria.getCategoria_Id_categoria());
        return getSimpleJdbcTemplate().queryForInt("SELECT last_insert_id()");
    }
    
    @Override
    public void actualizar(Subcategoria subcategoria) {

        getJdbcTemplate().update(
                "update subcategoria set de_subcategoria = ?, in_estado = ? where id_subcategoria = ?",
                subcategoria.getDe_subcategoria(), subcategoria.getIn_estado(), subcategoria.getId_subcategoria());       
    }

    
    @Override
    public void eliminar(Subcategoria subcategoria) {

        getJdbcTemplate().update(
                "delete from subcategoria where id_subcategoria = ?", subcategoria.getId_subcategoria());        
    } 
    
    
    @Override
    public Subcategoria buscar(int id_subcategoria) {
        try {
            return getSimpleJdbcTemplate().queryForObject(
                    "select * from subcategoria where id_subcategoria = ?",
                    new BeanPropertyRowMapper<Subcategoria>(Subcategoria.class), id_subcategoria);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
        
    
    @Override
    public List<Subcategoria> buscarTodos() {
        return getSimpleJdbcTemplate().query(
                "select de_categoria, in_estado from sub_categoria",
                new BeanPropertyRowMapper<Subcategoria>(Subcategoria.class));
    }    
    
    
}
